/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.finalist.Principal;
import com.finalist.entity.Member;
import com.finalist.service.MemberService;

/**
 * Interceptor - 会员权限
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
public class MemberInterceptor extends HandlerInterceptorAdapter
{

    private static final Log LOGGER = LogFactory.getLog(MemberInterceptor.class);

    /** 重定向视图名称前缀 */
    private static final String REDIRECT_VIEW_NAME_PREFIX = "redirect:";

    /** "会员"属性名称 */
    private static final String MEMBER_ATTRIBUTE_NAME = "member";

    /** 默认登录URL */
    private static final String DEFAULT_LOGIN_URL = "/login.jhtml";

    /** 登录URL */
    private String loginUrl = DEFAULT_LOGIN_URL;

    @Value("${url_escaping_charset}")
    private String urlEscapingCharset;

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {

        HttpSession session = request.getSession();
        Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
        if (principal != null)
        {
            return true;
        }
        else
        {
            String requestType = request.getHeader("X-Requested-With");
            if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest"))
            {
                response.addHeader("loginStatus", "accessDenied");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
            else
            {
                String jumpURL = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
                if (request.getRequestURI().startsWith(request.getContextPath() + "/weixin/"))
                {
                    request.getSession().setAttribute("mark", "0");
                }
                else
                {
                    request.getSession().setAttribute("mark", "1");
                }
                if (!request.getMethod().equalsIgnoreCase("GET"))
                {
                    jumpURL = "login@auth" + jumpURL;
                }
                try
                {
                    request.getSession().setAttribute("jumpURL", jumpURL);
                    request.getRequestDispatcher("/visitInterceptor.auth").forward(request, response);
                }
                catch (Exception e)
                {
                    LOGGER.error(e);
                }
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {
        if (modelAndView != null)
        {
            String viewName = modelAndView.getViewName();
            if (!StringUtils.startsWith(viewName, REDIRECT_VIEW_NAME_PREFIX))
            {
                modelAndView.addObject(MEMBER_ATTRIBUTE_NAME, this.memberService.getCurrent());
            }
        }
    }

    /**
     * 获取登录URL
     * 
     * @return 登录URL
     */
    public String getLoginUrl()
    {
        return this.loginUrl;
    }

    /**
     * 设置登录URL
     * 
     * @param loginUrl
     *            登录URL
     */
    public void setLoginUrl(String loginUrl)
    {
        this.loginUrl = loginUrl;
    }

}
